package main

import (
	"fmt"
	"net/http"
	"runtime"

	library "../../library"
	HTTP "../../library/http"
	file "../../library/httplib/file"
	protocol "../../library/httplib/protocol"
	log "../../library/log"
)

// Debug 调试
const Debug = false

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	// 初始化日志
	l := log.DBLog{}
	l.Init("log.db")
	log.SetLog("library", &l.Port)
}
func main() {
	defer log.GetLog("library").Close() // 关闭日志
	// http 服务
	H := &HTTP.HTTP{}
	// 初始化
	H.Init(1000, 8000)
	// 初始化路由
	if !Debug {
		Skip(H) // 跳转到主页
	}
	File(H)          // 文件服务
	ErrorToSubmit(H) // 前端错误日志
	// 启动
	H.Listen(":80")
}

// Skip 路由跳转
func Skip(H *HTTP.HTTP) {
	// 路由
	skip := &protocol.Protocol{
		Path:         `/`,
		ProtocolType: "GET",
		// 处理过程
		Processor: func(w http.ResponseWriter, r *http.Request, v map[string]interface{}) {
			http.Redirect(w, r, "/index.html", http.StatusFound)
		},
	}
	H.Handle[skip.Routing()] = skip
}

// File 文件路由
func File(H *HTTP.HTTP) {
	// ! 调试切换
	if !Debug {
		// * 初始化文件路由
		// !  注: 路径需要 / 作为结束
		(&file.File{
			HTTP:       H,
			RegExp:     true,
			UsingTypes: true,
			RemotePath: "/(.*?)",
		}).New("./Resource/", 300)
	} else {
		// * 测试用路由代码
		File := &protocol.Protocol{
			Path:         `/(.*?)`,
			RegExp:       true,
			ProtocolType: "GET",
			// 处理过程
			Processor: func(w http.ResponseWriter, r *http.Request, v map[string]interface{}) {
				http.StripPrefix("/", http.FileServer(http.Dir("./Resource"))).ServeHTTP(w, r)
			},
		}
		H.Handle[File.Routing()] = File
	}
}

// ErrorToSubmit 错误日志提交路由
func ErrorToSubmit(H *HTTP.HTTP) {
	var db = library.DB{Type: "sqlite3"}
	// 打开本地文件
	db.OpenFile("./ErrorToSubmit.db")
	// 创建数据库
	_, err := db.GetDB().Exec(`CREATE TABLE IF NOT EXISTS "ErrorToSubmit"("Error" TEXT,"URL" TEXT);`)
	if err != nil {
		panic(fmt.Sprintf("创建数据表失败: %v", err))
	}
	// 路由
	Error := &protocol.Protocol{
		Path:         `/ErrorToSubmit`,
		RegExp:       true,
		ProtocolType: "GET",
		// 处理过程
		Processor: func(w http.ResponseWriter, r *http.Request, v map[string]interface{}) {
			strU := ""
			strE := ""
			if valU, ok := v["URL"]; ok {
				strU = fmt.Sprint(valU)
			}
			if valE, ok := v["Error"]; ok {
				strE = fmt.Sprint(valE)
			}
			if strU != "" || strE != "" {
				db.SetExec(`INSERT INTO ErrorToSubmit(URL,Error) values(?,?)`, strU, strE)
			}
		},
	}
	H.Handle[Error.Routing()] = Error
}
